package com.tsingteng.cosfun.ui.search;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cy.cyflowlayoutlibrary.FlowLayout;
import com.cy.cyflowlayoutlibrary.FlowLayoutAdapter;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BasePresenterFragment;
import com.tsingteng.cosfun.bean.FollowBean;
import com.tsingteng.cosfun.bean.SearchResp;
import com.tsingteng.cosfun.bean.SearchUserResp;
import com.tsingteng.cosfun.callback.AppListener;
import com.tsingteng.cosfun.common.BroadcastManager;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.ui.mine.HomeMineFragment;
import com.tsingteng.cosfun.ui.mine.TerminalActivity;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.widget.MyRecycleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索功能
 * author : zht
 */
public class SearchActivity extends BasePresenterFragment<SearchPresenter, SearchContact.ISearchView> implements SearchContact.ISearchView, TextWatcher
        , RecommentAdapter.SearchFanListener ,SearchInitAdapter.FocusSearchListener  {

    @BindView(R.id.search_et)
    EditText mSearchEt;
    @BindView(R.id.search_cancel_tv)
    TextView mSearchCancelTv;
    @BindView(R.id.search_his_tv)
    TextView mSearchHisTv;
    @BindView(R.id.cancel_his_tv)
    TextView mCancelHisTv;
    @BindView(R.id.search_flow)
    FlowLayout mSearchFlow;
    @BindView(R.id.search_his_rl)
    RelativeLayout mSearchHisRl;
    @BindView(R.id.search_lv)
    ListView mSearchLv;
    @BindView(R.id.et_close)
    ImageView mEtClose;
    int pageNo = 1;
    @BindView(R.id.fan_listview)
    MyRecycleView mFanListView;
    @BindView(R.id.search_rl)
    RelativeLayout mSearchRl;
    @BindView(R.id.none_tv)
    TextView mNoneTv;
    @BindView(R.id.found_num_tv)
    TextView mFoundNumTv;
    @BindView(R.id.num_ll)
    LinearLayout mNumll;
    @BindView(R.id.rankLin)
    LinearLayout rankLin;
    @BindView(R.id.know_tv)
     TextView mKnowTv;
    SearchInitAdapter initAdapter;
    FlowLayoutAdapter<String> mFlowadapter;
    int page_no = 1;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    private List<String> history(String content) {
        List<String> list = new ArrayList<>();
        String history = LogonUtils.getSearchHistory();
        if (TextUtils.isEmpty(history)) {
            mSearchHisRl.setVisibility(View.GONE);
            mSearchFlow.setVisibility(View.GONE);
        } else {
            if (TextUtils.isEmpty(content)) {
                mSearchHisRl.setVisibility(View.VISIBLE);
                mSearchFlow.setVisibility(View.VISIBLE);
            }
            String[] historys = history.split(",");
            if (historys.length > 9) {
                for (int i = 0; i < 10; i++) {
                    if (!TextUtils.isEmpty(historys[i])) {
                        list.add(historys[i]);
                    }
                }
            } else {
                for (String str : historys) {
                    if (!TextUtils.isEmpty(str)) {
                        list.add(str);
                    }
                }
            }
        }
        return list;
    }

    @Override
    protected void initData(View rootView) {
        mSearchEt.addTextChangedListener(this);
        List<String> list = history("");
        mPresenter.getCommenList(Constant.SEARCH_PAGE_RECOMMENDATION, pageNo);
        mFlowadapter = new FlowLayoutAdapter<String>(list) {
            @Override
            public void bindDataToView(ViewHolder holder, int position, String bean) {
                holder.setText(R.id.search_tv, bean);
            }

            @Override
            public void onItemClick(int position, String bean) {
                mSearchEt.setText(bean);
                LogonUtils.setSearchHis(bean);
                List<String> listHis = history("");
                mFlowadapter.clearAddAll(listHis);
                page_no = 1;
                mPresenter.getSearchList(bean,page_no);
            }

            @Override
            public int getItemLayoutID(int position, String bean) {
                return R.layout.search_item_tv;
            }
        };
        mSearchFlow.setAdapter(mFlowadapter);
//        if (null !=getActivity())
//        KeyBoardUtils.observeSoftKeyboard(getActivity(), (softKeybardHeight, visible) -> {
//            if (visible){
//                page_no = 1;
//                mAdapter.getData().clear();
//                String content = mSearchEt.getText().toString().trim();
//                if (!TextUtils.isEmpty(content)) {
//                    addFlow(content);
//                    mPresenter.getSearchList(content, page_no);
//                }
//            }
//        });
    }

    @Override
    protected SearchPresenter createPresenter() {
        return new SearchPresenter();
    }

    @Override
    protected View initHeader() {
        return null;
    }

    @Override
    protected MyRecycleView createRecycleView() {
        return mFanListView;
    }

    @Override
    protected RecommentAdapter createAdapter() {
        return new RecommentAdapter(getContext(), this);
    }

    @Override
    protected void refresh() {
          page_no = 1;
          mAdapter.getData().clear();
          String content = mSearchEt.getText().toString().trim();
          mPresenter.getSearchList(content,page_no);

    }

    @OnClick({R.id.cancel_his_tv, R.id.search_cancel_tv, R.id.iv_search_left, R.id.et_close})
    void onclick(View view) {
        switch (view.getId()) {
            case R.id.et_close:
                mSearchEt.setText("");
                break;
            case R.id.search_rl:
                break;
            case R.id.iv_search_left:
                if (null !=getActivity())
                getActivity().finish();
                break;
            case R.id.cancel_his_tv:
                LogonUtils.clearSearchHis();
                mSearchHisRl.setVisibility(View.GONE);
                mSearchFlow.setVisibility(View.GONE);
                break;
            case R.id.search_cancel_tv:
                String etContent = mSearchEt.getText().toString().trim();
                if (TextUtils.isEmpty(etContent)) {
                    showToast(getResources().getString(R.string.input));
                    return;
                }
                addFlow(etContent);
                mPresenter.getSearchList(etContent,page_no);
                break;
        }
    }
   void addFlow(String content){
       LogonUtils.setSearchHis(content);
       List<String> listHis = history("search");
       mFlowadapter.clearAddAll(listHis);
   }
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        String content = mSearchEt.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            mEtClose.setVisibility(View.GONE);
            mFanListView.setVisibility(View.GONE);
            mSearchLv.setVisibility(View.VISIBLE);
            mNoneTv.setVisibility(View.GONE);
            mNumll.setVisibility(View.GONE);
            List<String> listHis = history("");
            if (0 != listHis.size()) {
                mSearchHisRl.setVisibility(View.VISIBLE);
            }else{
                mSearchHisRl.setVisibility(View.GONE);
            }
            mSearchFlow.setVisibility(View.VISIBLE);
        } else {
            mEtClose.setVisibility(View.VISIBLE);
        }
        if (content.length() > 15) {
            showToast(getResources().getString(R.string.most));
        }
    }

    @Override
    public void showSearch(SearchResp list) {
        mSearchHisRl.setVisibility(View.GONE);
        mSearchFlow.setVisibility(View.GONE);
        if (null == list || null == list.getData() || 0 == list.getData().size()) {
            mNoneTv.setVisibility(View.VISIBLE);
            mNumll.setVisibility(View.GONE);
            mFanListView.setVisibility(View.GONE);
            mSearchLv.setVisibility(View.VISIBLE);
            return;
        }
        mNoneTv.setVisibility(View.GONE);
        mFanListView.refreshComplete();
        mFanListView.setVisibility(View.VISIBLE);
        mNumll.setVisibility(View.VISIBLE);
        if (1 == page_no) {
            if (null !=mAdapter.getData())
                mAdapter.getData().clear();
        }
        mAdapter.addData(list.getData());
        String etContent = "“"+mSearchEt.getText().toString()+"”";
        String content = getResources().getString(R.string.find)+mAdapter.getData().size()+getResources().getString(R.string.ge);
        if (mAdapter.getData().size()<2){
            rankLin.setVisibility(View.VISIBLE);
            mSearchLv.setVisibility(View.VISIBLE);
        }else {
            mSearchLv.setVisibility(View.GONE);
            rankLin.setVisibility(View.GONE);
        }
        mKnowTv.setText(etContent);
        mFoundNumTv.setText(content);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showCommenList(SearchResp list) {
        if (null == list || null == list.getData() || 0 == list.getData().size()) {
            return;
        }
        mFanListView.setVisibility(View.GONE);
        mSearchLv.setVisibility(View.VISIBLE);
        mNoneTv.setVisibility(View.GONE);
        initAdapter = new SearchInitAdapter(getContext(), list.getData(), this);
        mSearchLv.setAdapter(initAdapter);
    }
    @Override
    public void searchFocus(int position, SearchUserResp bean) {
        if (!LogonUtils.chckLogon(getActivity(), false, 4)) return;
        if (null == bean) {
            return;
        }
        if (0 == initAdapter.getItem(position).getIsAttention()) {
            initAdapter.getItem(position).setIsAttention(1);
            initAdapter.notifyDataSetChanged();
            mPresenter.loginFollowFans(bean.getProfileId() + "");
        } else {
            initAdapter.getItem(position).setIsAttention(0);
            initAdapter.notifyDataSetChanged();
            mPresenter.loginNoFollow(bean.getProfileId() + "", position);
        }
        AppListener.OnAttentFocusBackListener listener = AppListener.getInstance().getOnAttentFocusBackListener();
        if (null !=listener){
            listener.onAttentBack();
        }
    }

    @Override
    public void clickImage(int position, SearchUserResp bean) {
        if (null == bean){
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putInt("user_id", bean.getProfileId());
        bundle.putInt(Constant.TAG, 1);
        TerminalActivity.showFragment(getContext(), HomeMineFragment.class, bundle);
    }

    @Override
    public void getFollowResult(FollowBean followBean) {
        ToastUtils.showToast(getResources().getString(R.string.focused));
    }

    @Override
    public void showNoFollowResult(FollowBean followBean, int position) {
        Toast.makeText(getContext(), getResources().getString(R.string.cancel_focus), Toast.LENGTH_LONG).show();
    }

    @Override
    public void searchFanListener(int position, SearchUserResp listResp) {
        if(mFanListView.getIsRefreshing()){
            return;
        }
        if (!LogonUtils.chckLogon(getActivity(), false, 4)) return;
        if (null == listResp) {
            return;
        }
        SearchUserResp mSearchUser = ((SearchUserResp)mAdapter.getItem(position));
        if (null == mSearchUser){
            return;
        }

        if (0 == mSearchUser.getIsAttention()) {
            mSearchUser.setIsAttention(1);
            mAdapter.notifyDataSetChanged();
            mPresenter.loginFollowFans(listResp.getProfileId() + "");
        } else {
            mSearchUser.setIsAttention(0);
            mAdapter.notifyDataSetChanged();
            mPresenter.loginNoFollow(listResp.getProfileId() + "", position);
        }
    }

    @Override
    public void clickImages(int position, SearchUserResp listResp) {
        if(mFanListView.getIsRefreshing()){
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putInt("user_id",listResp.getProfileId());
        bundle.putInt(Constant.TAG, 1);
        TerminalActivity.showFragment(getContext(), HomeMineFragment.class, bundle);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onLoadMoreRequested() {
        if (mAdapter.getData().size()<10){
            return;
        }
         page_no++;
        String content = mSearchEt.getText().toString().trim();
        mPresenter.getSearchList(content,page_no);
    }
}
